﻿using System.Text;
using EmbeddedSharp.Core;
using EmbeddedSharp.Scripting.Function;

namespace EmbeddedSharp.Scripting
{
    public class EnhancedCSharpCodeTranslator : CSharpCodeTranslator
    {
        public EnhancedCSharpCodeTranslator(IFunctionManager funMgr)
            : base(funMgr)
        {
        }

        public EnhancedCSharpCodeTranslator(string className)
            : base(className)
        {
        }

        public override object Visit(FuncNode node)
        {
            if (node is UserDefinedFunctionNode)
            {
                return GenerateFunction(node);
            }

            return base.Visit(node);
        }

        public object GenerateFunction(FuncNode node)
        {
            UserDefinedFunctionNode udf =
                (UserDefinedFunctionNode)
                FunctionManager.GetFunction(
                // if the function specfies
                // use the class name
                // else use the current class
                node.Value.Contains(".") ? node.Value
                : this.ClassName + "." + node.Value);
            Utils.Debugging(node.Value);
            string expr = udf.FuncBody;

            StringBuilder buff = new StringBuilder();
            for (int index = 0; index < udf.Arguments.Length; index++)
            {
                buff.Append(udf.Parameters[index]);
                if (index + 1 < udf.Arguments.Length)
                {
                    buff.Append(",");
                }
            }

            string func = string.Format(@"
                    public object {0} {
                        {1}
                    }
                ", buff.ToString(), udf.FuncBody);

            return func;
        }
    }
}
